import React, { useEffect, useState } from "react";
import mascot from "@/assets/mascot.png";
import { DigitalEmployee } from "@/api/Home/home";
import { iconMap, defaultIcon } from "@/utils/iconMap";

interface EmployeeItem {
  id: number;
  name?: string;
  url?: string | null;
  phone?: string;
  flow?: string;
  position?: string;
  createdAt?: string;
  iconKey?: string; // 用来匹配头像的 key，比如 "01_s"
  [k: string]: any;
}

const EmployeeCard: React.FC<{ item: EmployeeItem; index: number }> = ({ item, index }) => {
  const handleCardClick = () => {
    if (item.url) {
      window.open(item.url, "_blank", "noopener,noreferrer");
    }
  };

  const safeText = (v?: string) => (v && v.length ? v : "--");
  const created = item.createdAt || item.createTime || "2025-01-01 00:00:00";

  // 头像选择逻辑：先看 item.iconKey -> 再用 index 映射 -> 最后用默认图
  const iconKey = item.iconKey || `${String(index + 1).padStart(2, "0")}_s`;
  const avatarSrc = iconMap[iconKey] || defaultIcon;

  return (
    <div
      onClick={handleCardClick}
      className="w-[340px] border border-gray-300 rounded-lg p-4 flex flex-col justify-between 
                 hover:shadow-lg transition-all duration-300 cursor-pointer 
                 active:scale-95 bg-white"
    >
      {/* 顶部信息 */}
      <div className="flex items-center">
        <img
          src={avatarSrc}
          alt={item.name || "staff"}
          className="w-[66px] h-auto mr-2 object-cover rounded-full"
        />
        <div>
          <div className="text-base font-semibold">{safeText(item.name)}</div>
        </div>
      </div>

      {/* 中间信息 */}
      {/* <div className="text-sm text-gray-600">
        <div>流程：{safeText(item.flow || "质量分析")}</div>
        <div>岗位：{safeText(item.position || "周月质量分析")}</div>
        <div>创建时间：{created}</div>
      </div> */}
    </div>
  );
};

const Dialogcard: React.FC = () => {
  const [list, setList] = useState<EmployeeItem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchList();
  }, []);

  const fetchList = async () => {
    setLoading(true);
    try {
      const res = await DigitalEmployee();
      const data = (res && res.data) || [];
      setList(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error("fetch DigitalEmployee failed", err);
      setList([]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex w-full min-h-[650px] items-start justify-center bg-white rounded-2xl p-6">
      <div className="flex flex-row items-start mr-10 gap-6">
        <img src={mascot} alt="吉祥物" className="w-[150px] h-auto" />
      </div>

      <div className="flex-1">
        {loading ? (
          <div className="text-center py-12">加载中...</div>
        ) : list.length === 0 ? (
          <div className="text-center py-12 text-gray-500">暂无智能体数据</div>
        ) : (
          <div className="grid grid-cols-3 gap-6 mt-6">
            {list.map((item, idx) => (
              <EmployeeCard key={item.id} item={item} index={idx} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default Dialogcard;
